package com.atguigu.interactive;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareData
{
    private int flag = 1; //标志位  A:1 B：2 C：3

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void print5() throws InterruptedException {
        lock.lock();
        try
        {
            //1 判断
            while (flag != 1)
            {
                condition1.await();
            }
            //2 干活
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            //3 通知
            flag = 2;
            condition2.signal();
        }finally {
            lock.unlock();
        }
    }
    public void print10() throws InterruptedException
    {
        lock.lock();
        try
        {
            //1 判断
            while (flag != 2)
            {
                condition2.await();
            }
            //2 干活
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            //3 通知
            flag = 3;
            condition3.signal();
        }finally {
            lock.unlock();
        }
    }
    public void print15() throws InterruptedException
    {
        lock.lock();
        try
        {
            //1 判断
            while (flag != 3)
            {
                condition3.await();
            }
            //2 干活
            for (int i = 1; i <=15; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i);
            }
            //3 通知
            flag = 1;
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }
}

public class ThreadOrderAccess
{

    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(() -> {for (int i = 0; i < 10; i++) {try{shareData.print5();} catch (InterruptedException e) {throw new RuntimeException(e);
                }
            }
        },"A").start();

        new Thread(() -> {for (int i = 0; i < 10; i++) {try{shareData.print10();} catch (InterruptedException e) {throw new RuntimeException(e);
        }
        }
        },"B").start();


        new Thread(() -> {for (int i = 0; i < 10; i++) {try{shareData.print15();} catch (InterruptedException e) {throw new RuntimeException(e);
        }
        }
        },"C").start();

    }
}
